<?php

namespace app\common\model;

use think\Model;

class Menu extends Model
{


    protected $table = 'qi_menu';

    protected $autoWriteTimestamp = 'datetime';
    protected $createTime = 'create_time';
    protected $updateTime = 'update_time';



    /*
     * 递归创建无级分类
     */
    public function getMenuRecursion($pid = 0){
        $data = $this->where('pid', $pid)->select()->toArray();

        $menuDatas = [];
        foreach($data as $item){
            $children['children'] = $this->getMenuRecursion($item['id']);
            $menuDatas[] = array_merge($item, $children);
        }
        return $menuDatas;
    }

    /*
     * 通过ID获取信息
     */
    public function getInfoById($id){
        return $this->where('id', $id)->find();
    }

    /*
     * 获取所有顶级菜单
     */
    public function getTopMenu(){
        $data = $this->where('pid', 0)->select();
        return $data;
    }


    /*
     * 添加菜单
     */
    public function addmenu($info){

        $this->data($info);

        $result = $this->save();
        return $result;
    }

    /*
     *更新菜单
     */
    public function editmenu($info){
        return $this->save($info, $info['id']);
    }


    /*
     * 删除菜单
     */
    public function delmenu($id){
        $hasSon = $this->where('pid', $id)->count();

        if($hasSon){
            exception('请先删除子菜单');
        }
        $return = $this->where('id', $id)->delete();
        return $return;
    }


}